package com.beagle.njddapp.ui.activity;

/**
 * @author hxx
 * @date 2021-06-09 11:32
 */
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.RotateAnimation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.beagle.njddapp.R;
import com.beagle.njddapp.core.LocationManager;
import com.beagle.njddapp.ui.adapter.PosListAdapter;
import com.beagle.njddapp.ui.adapter.inter.RecyclerViewItemClickLisenter;
import com.beagle.njddapp.utils.L;
import com.blankj.utilcode.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

public  class ChooseAeraActivity extends AppCompatActivity implements GeocodeSearch.OnGeocodeSearchListener, PoiSearch.OnPoiSearchListener, RecyclerViewItemClickLisenter<PoiItem> {

    private PosListAdapter mAdapter;



    private MapView mMapView;
    private AMap aMap = null;
    private RecyclerView rv;
//    private View rvHeadView;
    private ImageView ivLocation;
    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private String city;
    private int currentPage;
    private PoiSearch.Query query;
    private PoiSearch poiSearch;
    private List<PoiItem> poiItems;
    private PoiItem currentPos;
    private ImageView ivBack;
    private TextView tvTitle;
    private TextView tvRight;
    private TextView tvAddress;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_area);
        ivBack=findViewById(R.id.common_back_iv);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        tvAddress=findViewById(R.id.tv_address);
        tvTitle=findViewById(R.id.commom_title_tv);
        tvTitle.setText("选择位置");
        tvRight=findViewById(R.id.common_tv_right);
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("确定");
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentPos!=null){
                    Intent intent=new Intent();
                    intent.putExtra("pos",currentPos);
                    setResult(144,intent);
                    finish();
                }
            }
        });
        tvAddress.setText("当前位置："+LocationManager.getInstance().getLocation());
        tvAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.putExtra("loc",true);
                setResult(244,intent);
                finish();
            }
        });
        city=LocationManager.getInstance().getCityCode();
        initView(savedInstanceState);
        initData();
        setMapCenter(LocationManager.getInstance().location);
    }

    protected void initView(Bundle savedInstanceState) {

        mMapView = findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        rv = findViewById(R.id.rv);
        ivLocation = findViewById(R.id.iv_location);
        rv.setLayoutManager(new LinearLayoutManager(this));
        poiItems=new ArrayList<>();
        mAdapter = new PosListAdapter(poiItems,this);
        mAdapter.setOnItemClickLisenter(this);
        rv.setAdapter(mAdapter);
    }


    protected void initData() {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        //设置定位蓝点
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色    不显示范围圆圈
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色 不显示范围圆圈
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

        //设置缩放级别
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));

        // 控件交互 缩放按钮、指南针、定位按钮、比例尺等
        UiSettings mUiSettings;//定义一个UiSettings对象
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setMyLocationButtonEnabled(true); //显示默认的定位按钮
        aMap.setMyLocationEnabled(true);// 可触发定位并显示当前位置
        mUiSettings.setScaleControlsEnabled(true);//控制比例尺控件是否显示
        mUiSettings.setLogoPosition(AMapOptions.LOGO_MARGIN_LEFT);//设置logo位置


        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                animTranslate();
                setMarker(latLng);
                getGeocodeSearch(latLng);
                doSearchQuery(latLng);

            }
        });
        getGeocodeSearch(new LatLng(LocationManager.getInstance().getLatitude(),LocationManager.getInstance().getLongitude()));
        doSearchQuery(new LatLng(LocationManager.getInstance().getLatitude(),LocationManager.getInstance().getLongitude()));
    }


    private Marker centerMarker;
    private void setMarker(LatLng target) {
        if (centerMarker != null) centerMarker.remove();
        centerMarker = aMap.addMarker(new MarkerOptions().position(target).title("").snippet(""));
        Animation animation = new RotateAnimation(centerMarker.getRotateAngle() - 180, centerMarker.getRotateAngle(), 0, 0, 0);
//        Animation animation = new TranslateAnimation(target);
        animation.setDuration(360L);
        animation.setInterpolator(new LinearInterpolator());
        centerMarker.setAnimation(animation);
        centerMarker.startAnimation();
    }

    private AnimatorSet animatorSet;
    public void animTranslate(){
        if (animatorSet == null) {
            animatorSet = new AnimatorSet();
            animatorSet.playTogether(ObjectAnimator.ofFloat(ivLocation, "scaleX", 1, 0.5f, 1).setDuration(300)
                    , ObjectAnimator.ofFloat(ivLocation, "scaleY", 1, 0.5f, 1).setDuration(300));
        }animatorSet.start();
    }

    private GeocodeSearch geocoderSearch;

    //逆地理编码获取当前位置信息
    private void getGeocodeSearch(LatLng targe) {
        if (geocoderSearch == null) geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(targe.latitude, targe.longitude), 5000, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
    }

    protected void doSearchQuery(LatLng latLng) {

        currentPage = 0;
        query = new PoiSearch.Query(" ", " ", city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页

        LatLonPoint lpTemp = convertToLatLonPoint(latLng);

        if (lpTemp != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);  // 实现  onPoiSearched  和  onPoiItemSearched
            poiSearch.setBound(new PoiSearch.SearchBound(lpTemp, 5000, true));//
            // 设置搜索区域为以lp点为圆心，其周围5000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        }
    }
    public static LatLonPoint convertToLatLonPoint(LatLng latlon) {
        return new LatLonPoint(latlon.latitude, latlon.longitude);
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if (i != 1000) return;
        city=regeocodeResult.getRegeocodeAddress().getCityCode();
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }




    private void setMapCenter(AMapLocation amapLocation) {
        L.cc(amapLocation.toStr());
        aMap.animateCamera(CameraUpdateFactory.newCameraPosition(
                new CameraPosition(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude())
                        , 15, 0, 0)), 300, null); //设置地图中心点
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onPoiSearched(PoiResult result, int rcode) {
        if (rcode == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    if (result.getPois().size()>0){
                        poiItems.clear();
                        poiItems.addAll(result.getPois());
                        currentPos=poiItems.get(0);
                        mAdapter.setChoosePos(0);
                        mAdapter.notifyDataSetChanged();
                    }
//                    poiResult = result;
//                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
//                    List<SuggestionCity> suggestionCities = poiResult
//                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
//                    mDatas.clear();
//                    //if(isFirstLoadList || isBackFromSearchChoose){
//                    mDatas.add(mAddressEntityFirst);// 第一个元素
//
//                    AddressSearchTextEntity addressEntity = null;
//                    for (PoiItem poiItem : poiItems) {
//                        L.d("得到的数据 poiItem " + poiItem.getSnippet());
//                        addressEntity = new AddressSearchTextEntity(poiItem.getTitle(), poiItem.getSnippet(), false, poiItem.getLatLonPoint());
//                        mDatas.add(addressEntity);
//                    }
//                    if (isHandDrag) {
//                        mDatas.get(0).isChoose = true;
//                    }
//                    mRvAddressAdapter.notifyDataSetChanged();
                }
            } else {
                ToastUtils.showShort( "对不起，没有搜索到相关数据！");
            }
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onItemClickLisenter(PoiItem poiItem) {
        currentPos=poiItem;
    }
}